package com.cn.shuangzi.permission;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;

import com.cn.shuangzi.R;
import com.cn.shuangzi.SZApp;
import com.cn.shuangzi.permission.callback.OnPermissionCallback;
import com.cn.shuangzi.view.AlertWidget;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;


/**
 * Created by CN on 2017-10-11.
 */

public class RequestPermissionHelper implements OnPermissionCallback {
    private RequestPermissionViewP requestPermissionViewP;
    private PermissionHelper permissionHelper;
    private String[] permissionArrays;
    private int[] permissionInfo;
    private Activity context;
    private boolean isAlertOnPermissionReallyDeclined;
    private boolean isForceAccepting;

    public RequestPermissionHelper(Activity context, RequestPermissionViewP requestPermissionViewP, String[]
            permissionArrays, int[] permissionInfo, boolean isAlertOnPermissionReallyDeclined) {
        this.context = context;
        this.requestPermissionViewP = requestPermissionViewP;
        this.permissionArrays = permissionArrays;
        this.permissionInfo = permissionInfo;
        this.isAlertOnPermissionReallyDeclined = isAlertOnPermissionReallyDeclined;
        permissionHelper = PermissionHelper.getInstance(context, this);
        isForceAccepting = true;
    }

    public void checkPermissions() {
        permissionHelper
                .setForceAccepting(isForceAccepting) // default is false. its here so you know that it exists.
                .request(permissionArrays);
    }

    public void checkPermissionsWithoutForceAccepting() {
        isForceAccepting = false;
        permissionHelper
                .setForceAccepting(isForceAccepting) // default is false. its here so you know that it exists.
                .request(permissionArrays);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //返回时重新进行检查
        if (requestCode == permissionHelper.REQUEST_APP_DETAILS_SETTING) {
            checkPermissions();
        }
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
            grantResults) {
        permissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onPermissionGranted(@NonNull String[] permissionName) {
        String lastPermission = permissionName[permissionName.length - 1];
        if (lastPermission.equals(permissionArrays[permissionArrays.length - 1])) {
            //权限点击允许
            if (requestPermissionViewP != null) {
                requestPermissionViewP.onPermissionRequestSuccess(permissionName);
            }
        } else {
            checkPermissions();
        }
    }

    @Override
    public void onPermissionDeclined(@NonNull String[] permissionName) {
        if (requestPermissionViewP != null) {
            requestPermissionViewP.onRequestPermissionDeclined(permissionName);
        }
    }

    @Override
    public void onPermissionPreGranted(@NonNull String permissionsName) {
        if (requestPermissionViewP != null) {
            requestPermissionViewP.onPermissionRequestSuccess(permissionArrays);
        }
    }

    @Override
    public void onPermissionNeedExplanation(@NonNull String permissionName) {
        permissionHelper.requestAfterExplanation(permissionName);
    }

    @Override
    public void onPermissionReallyDeclined(@NonNull String[] permissionNames) {

        StringBuilder sb = new StringBuilder();
        List<String> permissionDieList = new ArrayList<>();
        int index = 1;
        for (int i = 0; i < permissionArrays.length; i++) {
            for (String permissionName : permissionNames) {
                if (permissionArrays[i].equals(permissionName)) {
                    if (i < permissionInfo.length) {
                        sb.append(index + "：" + SZApp.getInstance().getString(permissionInfo[i]));
                        permissionDieList.add(permissionArrays[i]);
                        ++index;
                    }
                }
                if (!"".equals(sb.toString())) {
                    sb.append("\n");
                }
            }
        }
        if (isAlertOnPermissionReallyDeclined) {
            if (context != null) {
                showRequestPermissionAlert(sb.toString(), permissionDieList.toArray(new String[permissionDieList.size()]));
            }
        } else {
            if (requestPermissionViewP != null) {
                requestPermissionViewP.onRequestPermissionAlertCancelled(permissionDieList.toArray(new String[permissionDieList.size()]));
            }
        }
    }

    @Override
    public void onNoPermissionNeeded() {
        if (requestPermissionViewP != null) {
            requestPermissionViewP.onPermissionRequestSuccess(permissionArrays);
        }
    }

    private AlertWidget alertWidgetPermission;

    private void showRequestPermissionAlert(final String permissionsNeed, final String[] permissionsName) {
        alertWidgetPermission = new AlertWidget(context);
        alertWidgetPermission.setCancelable(false);
        alertWidgetPermission.setTitle(context.getString(R.string.txt_hint_permissions_need));
        alertWidgetPermission.setOKListener(context.getString(R.string.txt_to_open), new DialogInterface
                .OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                toAppSetting();
            }
        });
        alertWidgetPermission.setCancelListener(context.getString(R.string.txt_to_no_open), new DialogInterface
                .OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (requestPermissionViewP != null) {
                    requestPermissionViewP.onRequestPermissionAlertCancelled(permissionsName);
                }
            }
        });
        alertWidgetPermission.setContent(permissionsNeed);
        alertWidgetPermission.show();
    }

    private void toAppSetting() {
        if (context != null) {
            context.startActivityForResult(getAppSettingIntent(), permissionHelper
                    .REQUEST_APP_DETAILS_SETTING);
        }
    }

    //获取应用设置界面Intent
    public static Intent getAppSettingIntent() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", SZApp.getInstance().getPackageName(), null);
        intent.setData(uri);
        return intent;
    }
}
